package com.cardmanage.service.impl;

import com.cardmanage.common.BaseContext;
import com.cardmanage.common.RedisConstants;
import com.cardmanage.common.Result;
import com.cardmanage.mapper.CardMapper;
import com.cardmanage.pojo.Card;
import com.cardmanage.pojo.NewCard;
import com.cardmanage.service.CardService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@RequiredArgsConstructor
@Service
public class CardServiceImpl implements CardService {
    private final CardMapper cardMapper;

    @Override
    public Result<Card> GetOne(Integer id) {
        Integer userId = BaseContext.getCurrentId();
        Card card = cardMapper.GetOne(id,userId);
        if(card == null) {
            return Result.error("表中无此数据");
        }
        card.setUserId(userId);
        return Result.success(card);
    }

    @Override
    public Result<List> GetAll() {
        Integer userId = BaseContext.getCurrentId();
        System.out.println("用户id"+userId);
        List<Card> cards = cardMapper.GetAll(userId);
        if (cards.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        System.out.println(cards);
        return Result.success(cards);
    }

    @Override
    public Result create(NewCard newCard) {
        BeanUtils.copyProperties(newCard,new Card());
        Integer userId = BaseContext.getCurrentId();
        String name = newCard.getName();
        String telephone = newCard.getTelephone();
        String email = newCard.getEmail();
        String company = newCard.getCompany();
        String post = newCard.getPost();
        String address = newCard.getAddress();
        String logoName = newCard.getLogoName();
        System.out.println(newCard);
        cardMapper.create(name,telephone,email,company,post,address,logoName,userId);
        return Result.success("创建成功");
    }

    @Override
    public Result editOne(Card card) {
        Integer userId = BaseContext.getCurrentId();
        Integer id = card.getId();
        String name = card.getName();
        String telephone = card.getTelephone();
        String email = card.getEmail();
        String company = card.getCompany();
        String post = card.getPost();
        String address = card.getAddress();
        String logoName = card.getLogoName();
        cardMapper.update(name,telephone,email,company,post,address,logoName,userId,id);
        return Result.success("修改成功");
    }

    @Override
    public Result delete(Integer id) {
        Integer userId = BaseContext.getCurrentId();
        cardMapper.delete(userId,id);
        return Result.success("删除成功");
    }
}
